﻿// plugin.js
; (function (undefined) {
    "use strict"
    var _global;

    // 工具函数
    // 对象合并
    function extend(o, n, override) {
        for (var key in n) {
            if (n.hasOwnProperty(key) && (!o.hasOwnProperty(key) || override)) {
                o[key] = n[key];
            }
        }
        return o;
    }
    // 自定义模板引擎
    function templateEngine(html, data) {
        var re = /<%([^%>]+)?%>/g,
            reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
            code = 'var r=[];\n',
            cursor = 0;
        var match;
        var add = function (line, js) {
            js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
                (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
            return add;
        }
        while (match = re.exec(html)) {
            add(html.slice(cursor, match.index))(match[1], true);
            cursor = match.index + match[0].length;
        }
        add(html.substr(cursor, html.length - cursor));
        code += 'return r.join("");';
        return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
    }
    // 通过class查找dom
    if (!('getElementsByClass' in HTMLElement)) {
        HTMLElement.prototype.getElementsByClass = function (n) {
            var el = [],
                _el = this.getElementsByTagName('*');
            for (var i = 0; i < _el.length; i++) {
                if (!!_el[i].className && (typeof _el[i].className == 'string') && _el[i].className.indexOf(n) > -1) {
                    el[el.length] = _el[i];
                }
            }
            return el;
        };
        ((typeof HTMLDocument !== 'undefined') ? HTMLDocument : Document).prototype.getElementsByClass = HTMLElement.prototype.getElementsByClass;
    }

    // 插件构造函数 - 返回数组结构
    function UserDialog(opt) {
        this._initial(opt);
    }
    UserDialog.prototype = {
        constructor: this,
        _initial: function (opt) {
            // 默认参数
            var def = {
                ok_txt: '确定',
                cancel_txt: '取消',
                loaded: function () { },
                confirm: function (data) { },
                close: function (data) { },
                content: '',
                template: '<select id="searchUserWin" ></select>',
                winWidth: '900px',
                winHeight: '600px',
                userData:[]
            };
            this._loadStyle();//加载样式和js 
            this.def = extend(def, opt, true); //配置参数
            this.dom = this._parseToDom(def.template)[0]; //存放在实例中的节点
            this.hasDom = false; //检查dom树中dialog的节点是否存在
            this.listeners = []; //自定义事件，用于监听插件的用户交互
            this.handlers = {};
            this.userData = '';
            this.show(function () { }); //弹出框

        },
        _loadStyle: function () {
            if ($('link[ref$="jquery.tree-multiselect.css"]').length == 0) {
                {
                    $('<link href="/content/treeMultiselect/jquery.tree-multiselect.css" rel="stylesheet" type="text/css" />').appendTo('head');
                    $('<script src= "/content/treeMultiselect/jquery.tree-multiselect.js" type= "text/javascript" />').appendTo('head');
                }
            }
        },
        _parseTpl: function (tmpId) { // 将模板转为字符串
            var data = this.def;
            var tplStr = document.getElementById(tmpId).innerHTML.trim();
            return templateEngine(tplStr, data);
        },
        _parseToDom: function (str) { // 将字符串转为dom
            var div = document.createElement('div');
            //div.setAttribute('style', 'display:none');
            //div.setAttribute('id','searchUserWinDiv');
            if (typeof str == 'string') {
                div.innerHTML = str;
            }
            return div.childNodes;
        },
        show: function (callback) {
            var _this = this;
            if (this.hasDom) return;
            if (this.listeners.indexOf('show') > -1) {
                if (!this.emit({ type: 'show', target: this.dom })) return;
            }
            document.body.appendChild(_this.dom);

            $.ajax({
                type: "GET",
                url: "/User/GetUtiltityUsers",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i) {
                        var userIds = _this.def.userData;
                        var selectedFlag = false;

                        $.each(userIds, function (uf) {
                            if (userIds[uf] == data[i].userId) {
                                selectedFlag = true;

                                return false;
                            }
                        });
                        //var opEle = '<option value="' + data[i].userId + '" data-section="' + data[i].orgFullName + '">' + data[i].name + '</option>';
                        var opEle = '<option value="' + data[i].userId + '" data-section="' + data[i].orgFullName+'" ' ;
                        if (selectedFlag){
                            opEle += ' selected';
                        }
                        opEle += '>' + data[i].name + '</option>';
                        $('#searchUserWin').append(opEle);
                    });

                    var options = { showSectionOnSelected: false, startCollapsed: true, searchable: true, searchParams: ['section', 'text'] };
                    $("select#searchUserWin").treeMultiselect(options);
                    var firstEle = $('.auxiliary').next().removeClass('collapsed');


                    this.hasDom = true;

                }, error: function (xhr, textStatus, errorThrown) {

                }
            });

            var layerIndex = layer.open({
                type: 1,
                title: "用户搜索", //不显示标题
                area: [_this.def.winWidth, _this.def.winHeight], //宽高
                content: $('#searchUserWin'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: [_this.def.ok_txt, _this.def.cancel_txt],
                yes: function () {
                    var newPerIds = "";
                    var userIds = $('.selected .item').each(function () {
                        newPerIds += $(this).attr('data-value') + ",";
                    });
                    newPerIds = newPerIds.substr(0, newPerIds.length - 1);

                    _this.userData = newPerIds;

                    if (_this.listeners.indexOf('confirm') > -1) {
                        _this.emit({ type: 'confirm', target: _this.dom, data: _this.userData });

                        layer.close(layerIndex);
                    }
                    !!_this.def.confirm && _this.def.confirm.call(this, _this.dom);

                    
                },
                no: function (index, layero) {
                    
                },
                success: function (layero, index) {
                    
                    //窗体加载成功
                    if (_this.listeners.indexOf('loaded') > -1) {
                        _this.emit({ type: 'loaded', target: _this.dom })
                    }
                    !!_this.def.confirm && _this.def.confirm.call(this, _this.dom);

                    
                },
                cancel: function (index, layero) {
                    
                    
                },
                end: function () {
                    document.body.removeChild(_this.dom);
                    $('.tree-multiselect').remove();
                }
            });
            callback && callback();
           
            return this;
        },
        on: function (type, handler) {
            // type: show, shown, hide, hidden, close, confirm
            if (typeof this.handlers[type] === 'undefined') {
                this.handlers[type] = [];
            }
            this.listeners.push(type);
            this.handlers[type].push(handler);
            return this;
        },
        
        emit: function (event) {
            if (!event.target) {
                event.target = this;
            }
            if (this.handlers[event.type] instanceof Array) {
                var handlers = this.handlers[event.type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    handlers[i](event);
                    return true;
                }
            }
            return false;
        }
    }

    // 最后将插件对象暴露给全局对象
    _global = (function () { return this || (0, eval)('this'); }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = UserDialog;
    } else if (typeof define === "function" && define.amd) {
        define(function () { return UserDialog; });
    } else {
        !('UserDialog' in _global) && (_global.UserDialog = UserDialog);
    }
}());
